﻿using Sustainalytics.DataLayer.EsgRatings;
using Sustainalytics.LongRunningTaskManager;
using Sustainalytics.LongRunningTaskManager.Interface;
using Sustainalytics.OAuth.Services.Common.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using Sustainalytics.Entities.ESGRatings;
using Sustainalytics.DataLayer;
using Sustainalytics.DataLayer.Shared;
using Newtonsoft.Json;
using System.IO;
using Sustainalytics.Utils;

namespace Sustainalytics.Portfolios.Tasks
{
    public class PortfolioMatchedSecuritiesDownloadTask : ILongRunningTask
    {
        public LongRunningTaskTypeEnum Type
        {
            get { return LongRunningTaskTypeEnum.PortfolioMatchedSecuritiesDownload; }
        }



        public object Start(LongRunningTaskContext context)
        {

            return CreateOWINController(context);
           
        }

        private ILongRunningTaskResult CreateOWINController(LongRunningTaskContext context)
        {
            OAuthClient oAuthClient = new OAuthClient(
                HostConfig.GetHostUrl() + HostConfig.GetMatchedSecurityResource() + "/token",
                HostConfig.GetHostUrl() + HostConfig.GetMatchedSecurityResource(),
                null,
                null);

            oAuthClient.SetAuthenticationTicket(context.Ticket);

            HttpResponseMessage resp = oAuthClient.PostAsync(null, new ObjectContent<string>(context.ParamJson, new JsonMediaTypeFormatter()), context.CancellationToken).Result;

            resp.EnsureSuccessStatusCode();

            // portfolio upload temporary folder
            var temporaryFolder = ConfigurationManager.AppSettings["portfolioUploadTempFolder"];

            if (string.IsNullOrEmpty(temporaryFolder))
            {
                throw new NullReferenceException("Portfolio temporary download folder not defined in appSettings :: portfolioMatchDownloadTempFolder.");
            }

            // ensure that the temporary folder exists
            try
            {
                if (Directory.Exists(temporaryFolder) == false)
                {
                    Directory.CreateDirectory(temporaryFolder);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Portfolio download temporary folder does not exist and couldn't be created. Path: {0}", temporaryFolder), ex);
            }

            // create multipart provider for obtaining content associated to multipart response content
            var multipartProvider = new MultipartFormDataStreamProvider(temporaryFolder);

            //retrieve data from multipart response
            resp.Content.ReadAsMultipartAsync(multipartProvider).Wait();

            // read portfolio file
            MultipartFileData portfolioMultipartFile = multipartProvider.FileData.FirstOrDefault();

            if (portfolioMultipartFile == null)
            {
                throw new Exception("No multipart portfolio file data.");
            }


            string portfolioNameParam = multipartProvider.FormData["portfolioNameParam"];
            var portfolioName = JsonConvert.DeserializeObject<string>(portfolioNameParam);

            string filePath = portfolioMultipartFile.LocalFileName;
            string fileName = RemoveIllegalCharacters.Remove(portfolioMultipartFile.Headers.ContentDisposition.FileName);
            string mimeType = portfolioMultipartFile.Headers.ContentType.MediaType;

            byte[] resFileBytes = File.ReadAllBytes(filePath);

            var inMemFileRes = new LongRunningTaskFileInMemResult
            {
                Contents = resFileBytes,
                FileName = fileName,
                MimeType = mimeType
            };

            context.TaskStatus.PortfolioName = portfolioName;

            return inMemFileRes;
        }

    }
}
